import {
  Bubble,
  Conversations,
  Sender,
  useXAgent,
  useXChat,
} from "@ant-design/x";
import { createStyles } from "antd-style";
import React, { useEffect, useState } from "react";

import { PlusOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Flex, type GetProp, Space } from "antd";
import { BACKEND_HOST_LOCAL } from "../../constants";

const defaultConversationsItems = [
  {
    key: "0",
    label: "Jira Knowledge",
  },
];

const useStyle = createStyles(({ token, css }) => {
  return {
    layout: css`
      width: 100%;
      min-width: 1000px;
      height: 722px;
      border-radius: ${token.borderRadius}px;
      display: flex;
      background: ${token.colorBgContainer};
      font-family: AlibabaPuHuiTi, ${token.fontFamily}, sans-serif;

      .ant-prompts {
        color: ${token.colorText};
      }
    `,
    menu: css`
      background: ${token.colorBgLayout}80;
      width: 280px;
      height: 100%;
      display: flex;
      flex-direction: column;
    `,
    conversations: css`
      padding: 0 12px;
      flex: 1;
      overflow-y: auto;
    `,
    chat: css`
      height: 100%;
      width: 100%;
      max-width: 700px;
      margin: 0 auto;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      padding: ${token.paddingLG}px;
      gap: 16px;
    `,
    messages: css`
      flex: 1;
    `,
    placeholder: css`
      padding-top: 32px;
    `,
    sender: css`
      box-shadow: ${token.boxShadow};
    `,
    logo: css`
      display: flex;
      height: 72px;
      align-items: center;
      justify-content: start;
      padding: 0 24px;
      box-sizing: border-box;

      img {
        width: 24px;
        height: 24px;
        display: inline-block;
      }

      span {
        display: inline-block;
        margin: 0 8px;
        font-weight: bold;
        color: ${token.colorText};
        font-size: 16px;
      }
    `,
    addBtn: css`
      background: #1677ff0f;
      border: 1px solid #1677ff34;
      width: calc(100% - 24px);
      margin: 0 12px 24px 12px;
    `,
  };
});

const Independent: React.FC = () => {
  // ==================== Style ====================
  const { styles } = useStyle();

  const [content, setContent] = useState("");

  const [conversationsItems, setConversationsItems] = useState(
    defaultConversationsItems
  );

  const [activeKey, setActiveKey] = useState(defaultConversationsItems[0].key);

  const [agent] = useXAgent<{ message: string }>({
    request: async ({ message }, { onSuccess, onUpdate }) => {
      const fullContent = `Streaming output instead of Bubble typing effect. You typed: ${message}`;
      let currentContent = "";

      const id = setInterval(() => {
        currentContent = fullContent.slice(0, currentContent.length + 2);
        onUpdate({ message: currentContent });

        if (currentContent === fullContent) {
          clearInterval(id);
          onSuccess({ message: fullContent });
        }
      }, 100);
    },
  });

  const { onRequest, messages, setMessages } = useXChat({
    agent,
  });

  useEffect(() => {
    if (activeKey !== undefined) {
      setMessages([]);
    }
  }, [activeKey]);

  const onAddConversation = () => {
    setConversationsItems([
      ...conversationsItems,
      {
        key: `${conversationsItems.length}`,
        label: `新建会话${conversationsItems.length}`,
      },
    ]);
    setActiveKey(`${conversationsItems.length}`);
  };

  const onConversationClick: GetProp<typeof Conversations, "onActiveChange"> = (
    key
  ) => {
    setActiveKey(key);
  };

  // ==================== Nodes ====================
  const logoNode = (
    <div className={styles.logo}>
      <img
        src={`${process.env.PUBLIC_URL}/knowledge.png`}
        draggable={false}
        alt="logo"
      />
      <span>dynabook Knowledge</span>
    </div>
  );
  const roles: GetProp<typeof Bubble.List, "roles"> = {
    ai: {
      placement: "start",
      typing: true,
      avatar: { icon: <UserOutlined />, style: { background: "#fde3cf" } },
    },
    local: {
      placement: "end",
      variant: "shadow",
      avatar: { icon: <UserOutlined />, style: { background: "#fde3cf" } },
    },
  };
  // ==================== Render =================
  return (
    <div className={styles.layout}>
      {/* 🌟 侧边栏 */}
      <div className={styles.menu}>
        {/* 🌟 Logo */}
        {logoNode}
        {/* 🌟 添加会话 */}
        <Button
          onClick={onAddConversation}
          type="link"
          className={styles.addBtn}
          icon={<PlusOutlined />}
        >
          新建会话
        </Button>
        {/* 🌟 会话管理 */}
        <Conversations
          items={conversationsItems}
          className={styles.conversations}
          activeKey={activeKey}
          onActiveChange={onConversationClick}
        />
      </div>
      {/* 🌟 主体 */}
      <div className={styles.chat}>
        {/* 🌟 输入框 */}
        <Flex vertical gap="middle">
          <Bubble.List
            roles={roles}
            style={{ maxHeight: 300 }}
            items={messages.map(({ id, message, status }) => ({
              key: id,
              role: status === "local" ? "local" : "ai",
              content: message,
            }))}
          />
          <Sender
            loading={agent.isRequesting()}
            value={content}
            onChange={setContent}
            onSubmit={(nextContent) => {
              onRequest({ message: nextContent });
              setContent("");
            }}
          />
        </Flex>
      </div>
    </div>
  );
};

export default Independent;
